import axios from 'axios'
import state from '../store/state'

const baseURL = 'http://localhost:3000'

export function request(config) {
  state.isLoading = true
  const instance = axios.create({
    baseURL,
    timeout: 5000,
    withCredentials: true
  })

  instance.interceptors.request.use(
    (config) => {
      return config
    },
    (error) => {
      state.isLoading = false
      return error
    }
  )

  instance.interceptors.response.use(
    (response) => {
      state.isLoading = false
      return response
    },
    (err) => {
      state.isLoading = false
      if (err.message === 'timeout of 5000ms exceeded') {
        return { code: 10, message: '请求超时' }
      } else {
        return { code: 500, message: '网络连接失败，请稍后重试' }
      }
    }
  )

  return instance(config)
}
